package com.edu.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.edu.entiy.User;


@WebFilter("/*")
public class LoginFilter implements Filter {

   
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }

	
	public void destroy() {
		// TODO Auto-generated method stub
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//转换请求类型
		HttpServletRequest httpServletRequest = (HttpServletRequest)request;
		HttpServletResponse httpServletResponse = (HttpServletResponse)response;
		//统一编码格式
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		//获取请求路径
		String url = httpServletRequest.getRequestURL().toString();
		System.out.println(url);
		if(url.contains("/login") || url.contains("static") || url.contains("codeServlet") || url.contains("register") || url.contains("check")) {
			chain.doFilter(request, response);
			return;
		}else {
			HttpSession session = httpServletRequest.getSession();
			User user = (User)session.getAttribute("user");
			if(user == null) {
				httpServletResponse.sendRedirect("/books/login.jsp");
			}else {
				chain.doFilter(httpServletRequest, httpServletResponse);
			}
		}	
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
